import os

from google.appengine.ext import db
from google.appengine.ext.webapp import template

from model import Category, Wiki

from tools import manager

class WikiManager(manager.Manager):
    """
    """
    def get_wiki_key(self, title):
        # get all wikis
        wiki_query = Wiki.all()
        wiki_query.filter('language =', self.language)
        wiki_query.filter('title =', title)

        wiki = wiki_query.get()
        if wiki:
            return wiki.key()

        else:
            return None

    def __get_wiki(self, wiki_key=None):
        """
        """
        # get the first wiki
        if not wiki_key:
            category_query = Category().all()
            category_query.filter('language =', self.language)
            category_query.order('position')
            category = category_query.get()

            wiki_query = Wiki().all()
            wiki_query.filter('language =', self.language)
            if category:
                wiki_query.filter('category =', category.key())
            wiki_query.order('position')

            # found a default wiki
            if wiki_query.count() > 0:
                return wiki_query.get()

            # create a new wiki
            else:
                return Wiki().get(self.new_wiki())

        # get the asked wiki
        else:
            #
            return Wiki().get(wiki_key)

    def get_menu(self):
        """
        """
        # get all categories
        category_query = Category.all()
        category_query.filter('language =', self.language)
        category_query.order('position')

        # get all wikis
        wiki_query = Wiki.all()
        wiki_query.filter('language =', self.language)
        wiki_query.order('position')

        # init menu
        menu = list()

        # set the menu content
        for category in category_query:

            # list of wikis for a category
            list_wikis = list()

            # look for a wiki
            for wiki in wiki_query:

                # wiki in the current category
                if wiki.category.key() == category.key():

                    # add the pag in the temp list
                    list_wikis.append(wiki)

            if len(list_wikis) > 0:
                # set a dict wih the category and temp wikis
                item_category = {
                        'category': category.title,
                        'wikis': list_wikis}

                # add the dict into the menu
                menu.append(item_category)

        # return the menu at the end
        return menu

    def show(self, wiki_key=None):
        """
        """
        # get the wiki
        wiki = self.__get_wiki(wiki_key)
        # update max size
        if wiki.html_content:
            wiki.html_content = wiki.html_content.replace('max_size=',
                        'max_size=%s' % self.size.width)

        # get the menu
        menu = self.get_menu()

        # set the template
        self.template_values['action'] = 'wiki'
        self.template_values['menu'] = menu
        self.template_values['wiki'] = wiki

        # find the template
        path = os.path.join(os.path.dirname(__file__),
                                '../templates', 'wiki', 'index.html')

        # display the wiki
        return template.render(path, self.template_values)

    def edit(self, wiki_key):
        """
        """
        # get the menu at first
        menu = self.get_menu()

        # get the wiki
        wiki = Wiki().get(wiki_key)

        # find the categories
        category_query = Category().all()
        category_query.filter('language =', self.language)

        # set the template for edit
        self.template_values['menu'] = menu
        self.template_values['wiki'] = wiki
        self.template_values['categories'] = category_query
        self.template_values['page'] = 'wiki'
        self.template_values['images'] = self.get_content_images()

        # find the template
        path = os.path.join(os.path.dirname(__file__),
                            '../templates', 'wiki', 'edit.html')

        # display the wiki
        return template.render(path, self.template_values)

    def new_wiki(self):
        """
        """
        # get the default categry
        query = Category().all()
        query.filter('language =', self.language)
        category = query.filter('title =', ' ').get()

        if not category:
            category = Category()

            category.title = db.Category(' ')

            category.position = 1

            # set the current language
            category.language = self.language

            category.put()

        # create the new wiki
        wiki = Wiki()

        # set the current language
        wiki.language = self.language

        # require a title
        wiki.title = db.Category(' ')

        # attach the new wiki with the default category
        wiki.category = category

        # current number of wiki in the category
        query = Wiki().all()
        query.filter('language =', self.language)
        query.filter('category =', category)

        # conut the filter result
        number_of_wikis = query.count()

        # set the new wiki position
        wiki.position = number_of_wikis + 1
        #
        wiki.put()

        return wiki.key()

    def delete(self, wiki_key):
        """
        """
        #
        wiki = Wiki().get(wiki_key)

        # get other wikis in the old category
        query = Wiki().all()
        query.filter('category =', wiki.category)
        query.filter('position >', wiki.position)

        # update other wiki position
        for w in query:
            old_position = w.position - 1
            w.position = old_position
            w.put()

        # delete the wiki
        wiki.delete()

    def save(self, wiki_key, title, content):
        """
        """
        #
        wiki = Wiki().get(wiki_key)

        # title can t be empty
        title = title.strip()
        if title == '':
            title = ' '

        # set title
        wiki.title = db.Category(title)

        # set content
        wiki.content = content
        wiki.html_content = self.get_html_content(content)

        if not wiki.position:

            # retrieve the wiki to be updated
            query = Wiki().all()
            query.filter('category', wiki.category)
            # count
            nb_of_wikis = query.count()

            wiki.position = nb_of_wikis

        # save wiki
        wiki.put()
